from time import sleep
from autobahn.twisted.wamp import ApplicationSession
from twisted.internet.defer import inlineCallbacks
from eDIP43A_Factory import eDIP43A_Factory
from eDIP43A_Driver import eDIP43A_Driver
from twisted.internet import reactor

class McuComponent(ApplicationSession):
   """
   MCU WAMP application component.
   """
   #----------------------------------------------------------------------
   def volumeChange(self, volume):
      """"""
      self.publish(u'com.myapp.mcu.on_volume_change', volume)

   @inlineCallbacks
   def onJoin(self, details):
      print("MyComponent ready! Configuration: {}".format(self.config.extra))

      port = self.config.extra['port']
      baudrate = self.config.extra['baudrate']
      debug = self.config.extra['debug']

      factory = eDIP43A_Factory(None, None)
            
      print('About to open serial port {0} [{1} baud] ..'.format(port, baudrate))
      try:
         driver = eDIP43A_Driver(factory, port, reactor, baudrate=baudrate)
         factory.onVolumeChange = self.volumeChange
         
      except Exception as e:
         print('Could not open serial port: {0}'.format(e))
         self.leave()
      else:
         try:
            yield self.register(driver.protocol.VolumeDown, u"com.myapp.mcu.volume_down")
         except Exception as e:
            print ('Could not register method: {0}'.format(e))
         
         
         try:
            yield self.register(driver.protocol.VolumeUp, u"com.myapp.mcu.volume_up")
         except Exception as e:
            print ('Could not register method: {0}'.format(e))
         

